import numpy as np

# 创建一个示例矩阵
A = np.array([[1, 2],
              [3, 4]], dtype=float)

print("原始矩阵 A:")
print(A)

# 执行SVD分解
U, S, Vh = np.linalg.svd(A)

print("\n左奇异向量矩阵 U:")
print(U)
print("\n奇异值 S:")
print(S)
print("\n右奇异向量矩阵 Vh:")
print(Vh)



Sigma = np.zeros_like(A, dtype=float)
Sigma[:len(S), :len(S)] = np.diag(S)
print(Sigma)
Sigma = [[5.4649857 , 0.        ],
 [0.      ,   0.36596619]]

A_reconstructed = U @ Sigma @ Vh
print("重建的矩阵:")
print(A_reconstructed)
print("重建误差:", np.linalg.norm(A - A_reconstructed))


def low_rank_approximation(A, k):
    """矩阵的低秩近似"""
    U, S, Vh = np.linalg.svd(A, full_matrices=False)

    # 保留前k个奇异值
    U_k = U[:, :k]
    S_k = S[:k]
    Vh_k = Vh[:k, :]

    # 重建低秩矩阵
    A_approx = U_k @ np.diag(S_k) @ Vh_k
    return A_approx


# 示例
A = np.random.rand(5, 3)
A_approx = low_rank_approximation(A, 2)
print("原始矩阵形状11:", A.shape)
print("近似矩阵形状11:", A_approx.shape)
print("近似误差11:", np.linalg.norm(A - A_approx))